package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"

	"go-train/w3/server"

	"golang.org/x/sync/errgroup"
)

func main() {
	ctxB, cancel := context.WithCancel(context.Background())
	a1 := server.NewHttpServer(server.Listen("127.0.0.1:8081"))
	a2 := server.NewHttpServer(server.Listen("127.0.0.1:8082"))
	g, ctx := errgroup.WithContext(ctxB)
	g.Go(func() error {
		<-ctx.Done() // wait for stop signal
		return a1.Stop()
	})
	g.Go(func() error {
		return a1.Start()
	})
	g.Go(func() error {
		<-ctx.Done() // wait for stop signal
		return a2.Stop()
	})
	g.Go(func() error {
		return a2.Start()
	})

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGKILL, syscall.SIGINT, syscall.SIGQUIT)
	g.Go(func() error {
		for {
			select {
			case <-ctx.Done():
				return ctx.Err()
			case <-c:
				cancel()
				return nil
			}
		}
	})
	if err := g.Wait(); err != nil {
		log.Panicf("%v", err)
	}
}
